package com.orangeforms.webadmin.app.controller;

import cn.jimmyshi.beanquery.BeanQuery;
import com.github.pagehelper.page.PageMethod;
import com.orangeforms.common.core.annotation.MyRequestBody;
import com.orangeforms.common.core.constant.ErrorCodeEnum;
import com.orangeforms.common.core.object.*;
import com.orangeforms.common.core.util.MyCommonUtil;
import com.orangeforms.common.core.util.MyModelUtil;
import com.orangeforms.common.core.util.MyPageUtil;
import com.orangeforms.webadmin.app.dto.SysProjectDto;
import com.orangeforms.webadmin.app.model.SysProject;
import com.orangeforms.webadmin.app.service.SysProjectService;
import com.orangeforms.webadmin.app.vo.SysProjectVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashSet;
import java.util.List;
import java.util.Map;

/**
 * OrangeSingleDemo SysProjectController class
 *
 * @author xisheng
 * @date 2022/08/12
 */
@Slf4j
@RestController
@RequestMapping("/admin/app/sysProject")
public class SysProjectController {

    @Autowired
    private SysProjectService sysProjectService;


    @PostMapping("/add")
    public ResponseResult<Long> add(@MyRequestBody SysProjectDto sysProjectDto) {
        String erroMessage = MyCommonUtil.getModelValidationError(sysProjectDto,false);
        if(erroMessage != null){
            return ResponseResult.error(ErrorCodeEnum.DATA_VALIDATED_FAILED,erroMessage);
        }
        SysProject sysProject = MyModelUtil.copyTo(sysProjectDto,SysProject.class);
        sysProject = sysProjectService.saveNew(sysProject);
        return ResponseResult.success(sysProject.getId());
    }

    @PostMapping("/update")
    public ResponseResult<Void> update(@MyRequestBody SysProjectDto sysProjectDto) {
        String errorMessage = MyCommonUtil.getModelValidationError(sysProjectDto,true);
        if(errorMessage != null){
            return ResponseResult.error(ErrorCodeEnum.DATA_VALIDATED_FAILED,errorMessage);
        }
        SysProject sysProject = MyModelUtil.copyTo(sysProjectDto,SysProject.class);
        SysProject originalSysProject = sysProjectService.getById(sysProject.getId());
        if (originalSysProject == null) {
            errorMessage = "数据验证失败，当前 [数据] 并不存在，请刷新后重试！";
            return ResponseResult.error(ErrorCodeEnum.DATA_NOT_EXIST,errorMessage);
        }
        if(!sysProjectService.update(sysProject,originalSysProject)) {
            return ResponseResult.error(ErrorCodeEnum.DATA_NOT_EXIST);
        }
        return ResponseResult.success();
    }

    @PostMapping("/delete")
    public ResponseResult<Void> delete(@MyRequestBody Long id) {
        String errorMessage;
        if (MyCommonUtil.existBlankArgument(id)) {
            return ResponseResult.error(ErrorCodeEnum.ARGUMENT_NULL_EXIST);
        }
        return this.doDelete(id);
    }

    @PostMapping("/list")
    public ResponseResult<MyPageData<SysProjectVo>> list(
            @MyRequestBody SysProjectDto sysProjectDtoFilter,
            @MyRequestBody MyOrderParam orderParam,
            @MyRequestBody MyPageParam pageParam) {

        if (pageParam != null) {
            PageMethod.startPage(pageParam.getPageNum(),pageParam.getPageSize());
        }
        SysProject sysProjectFilter = MyModelUtil.copyTo(sysProjectDtoFilter,SysProject.class);
        String orderBy = MyOrderParam.buildOrderBy(orderParam,SysProject.class);
        List<SysProject> sysProjectList = sysProjectService.getSysProjectListWithRelation(sysProjectFilter,orderBy);
        return ResponseResult.success(MyPageUtil.makeResponseData(sysProjectList,SysProject.INSTANCE));
    }

    @GetMapping("/view")
    public ResponseResult<SysProjectVo> view(@RequestParam Long id) {
        log.info("view:{}",id);
        if (MyCommonUtil.existBlankArgument(id)) {
            return ResponseResult.error(ErrorCodeEnum.ARGUMENT_NULL_EXIST);
        }
        SysProject sysProject = sysProjectService.getByIdWithRelation(id, MyRelationParam.full());
        if (sysProject == null) {
            return ResponseResult.error(ErrorCodeEnum.DATA_NOT_EXIST);
        }
        SysProjectVo sysProjectVo = SysProject.INSTANCE.fromModel(sysProject);
        return ResponseResult.success(sysProjectVo);
    }

    @PostMapping("/listDictByIds")
    public ResponseResult<List<Map<String, Object>>> listDictByIds(@MyRequestBody List<Long> dictIds) {
        List<SysProject> resultList = sysProjectService.getInList(new HashSet<>(dictIds));
        return ResponseResult.success(BeanQuery.select(
                "id as id", "shorthand as name").executeFrom(resultList));
    }

    @GetMapping("/listDict")
    public ResponseResult<List<Map<String, Object>>> listDict(SysProject filter) {
        log.info("打印listDict");
        List<SysProject> resultList = sysProjectService.getListByFilter(filter);
        return ResponseResult.success(BeanQuery.select(
                "id as id", "shorthand as name").executeFrom(resultList));
    }

    private ResponseResult<Void> doDelete(Long id) {
        String errorMessage;
        // 验证关联Id的数据合法性
        SysProject originalSysProject = sysProjectService.getById(id);
        if (originalSysProject == null) {
            // NOTE: 修改下面方括号中的话述
            errorMessage = "数据验证失败，当前 [对象] 并不存在，请刷新后重试！";
            return ResponseResult.error(ErrorCodeEnum.DATA_NOT_EXIST, errorMessage);
        }
        // NOTE: 如果该对象的删除前数据一致性验证和实际需求有偏差，可以根据需求调整验证字段，甚至也可以直接删除下面的验证。
        // 删除前，先主动验证是否存在关联的从表数据。
        CallResult callResult = sysProjectService.verifyRelatedDataBeforeDelete(originalSysProject);
        if (!callResult.isSuccess()) {
            return ResponseResult.errorFrom(callResult);
        }
        if (!sysProjectService.remove(id)) {
            errorMessage = "数据操作失败，删除的对象不存在，请刷新后重试！";
            return ResponseResult.error(ErrorCodeEnum.DATA_NOT_EXIST, errorMessage);
        }
        return ResponseResult.success();
    }

}
